package com.ruoyi.system.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.aliyuncs.exceptions.ClientException;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.vo.EnterpriseInfoVO;
import com.ruoyi.system.dto.AliyunSmsDTO;
import com.ruoyi.system.mapper.GwEnterpriseInfoMapper;
import com.ruoyi.system.mapper.GwStaffMapper;
import com.ruoyi.system.mapper.GwSystemConfigMapper;
import com.ruoyi.system.service.*;
import com.ruoyi.system.utils.SendSmsUtil;
import com.ruoyi.system.utils.WeChatUtil;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 员工管理Service业务层处理
 *
 * @author ruoyi
 * @date 2025-04-27
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class GwStaffServiceImpl implements IGwStaffService {

    @Resource
    private GwStaffMapper gwStaffMapper;
    @Resource
    private IGwStaffBaseService gwStaffBaseService;
    @Resource
    private IGwStaffEducationService gwStaffEducationService;
    @Resource
    private IGwStaffWorkService gwStaffWorkService;
    @Resource
    private IGwContractService gwContractService;
    @Resource
    private GwEnterpriseInfoMapper gwEnterpriseInfoMapper;
    @Resource
    private GwSystemConfigMapper gwSystemConfigMapper;
    @Resource
    private SendSmsUtil sendSmsUtil;
    @Resource
    private WeChatUtil weChatUtil;

    /**
     * 查询员工管理
     *
     * @param id 员工管理主键
     * @return 员工管理
     */
    @Override
    public GwStaff selectGwStaffById(String id) {
        GwStaff gwStaff = gwStaffMapper.selectGwStaffById(id);
        //员工信息
        GwStaffBase gwStaffBaseQuery = new GwStaffBase();
        gwStaffBaseQuery.setStaffId(id);
        List<GwStaffBase> gwStaffBases = gwStaffBaseService.selectGwStaffBaseList(gwStaffBaseQuery);
        if (ObjectUtils.isNotEmpty(gwStaffBases)) {
            gwStaff.setGwStaffBase(gwStaffBases.get(0));
        }
        //教育经历
        GwStaffEducation gwStaffEducationQuery = new GwStaffEducation();
        gwStaffEducationQuery.setStaffId(id);
        List<GwStaffEducation> gwStaffEducations = gwStaffEducationService.selectGwStaffEducationList(gwStaffEducationQuery);
        gwStaff.setGwStaffEducations(gwStaffEducations);
        //工作经历
        GwStaffWork gwStaffWorkQuery = new GwStaffWork();
        gwStaffWorkQuery.setStaffId(id);
        List<GwStaffWork> gwStaffWorks = gwStaffWorkService.selectGwStaffWorkList(gwStaffWorkQuery);
        gwStaff.setGwStaffWorks(gwStaffWorks);
        //合同信息
        List<GwContract> gwContracts = gwContractService.getGwContractByTypeAndUserId("员工关系", id, null);
        gwStaff.setGwContracts(gwContracts);
        return gwStaff;
    }

    /**
     * 查询员工管理列表
     *
     * @param gwStaff 员工管理
     * @return 员工管理
     */
    @Override
    public List<GwStaff> selectGwStaffList(GwStaff gwStaff) {
        //设置公司ID
        System.out.println("-----applet login enterpriseId:"+SecurityUtils.getLoginUser().getEnterpriseId()+"-------------------");
        String companyId = ObjectUtils.isNotEmpty(SecurityUtils.getLoginUser().getEnterpriseId()) ? SecurityUtils.getLoginUser().getEnterpriseId() : "-1";
        gwStaff.setCompanyId(companyId);
        //企业管理员看公司的
        if(!"1".equals(SecurityUtils.getLoginUser().getUser().getUserType())){
            //其他人看自己创建的
            gwStaff.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        }
        List<GwSystemConfig> gwSystemConfigs = gwSystemConfigMapper.selectGwSystemConfigList(new GwSystemConfig());
        if(ObjectUtils.isNotEmpty(gwSystemConfigs)){
            gwStaff.setRemindDays(gwSystemConfigs.get(0).getRemindDays());
        }
        return gwStaffMapper.selectGwStaffList(gwStaff);
    }

    /**
     * 新增员工管理
     *
     * @param gwStaff 员工管理
     * @return 结果
     */
    @Override
    public int insertGwStaff(GwStaff gwStaff) {
        // 设置公司ID
        if(ObjectUtils.isEmpty(SecurityUtils.getLoginUser().getEnterpriseId())){
            throw new GlobalException("未知的公司,请绑定公司再进行操作");
        }
        gwStaff.setCompanyId(SecurityUtils.getLoginUser().getEnterpriseId());
        //gwStaff.setId(IdUtils.fastSimpleUUID());
        gwStaff.setCreateTime(DateUtils.getNowDate());
        gwStaff.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        gwStaff.setUpdateTime(DateUtils.getNowDate());
        gwStaff.setUpdateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        gwStaffMapper.insertGwStaff(gwStaff);

        //添加员工信息
        GwStaffBase gwStaffBase = new GwStaffBase();
        if (ObjectUtils.isNotEmpty(gwStaff.getGwStaffBase())) {
            gwStaffBase = gwStaff.getGwStaffBase();
        }
        gwStaffBase.setStaffId(gwStaff.getId() + "");
        gwStaffBase.setCreateTime(DateUtils.getNowDate());
        gwStaffBase.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        gwStaffBase.setUpdateTime(DateUtils.getNowDate());
        gwStaffBase.setUpdateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        gwStaffBaseService.insertGwStaffBase(gwStaffBase);
        //添加教育经历
        if (ObjectUtils.isNotEmpty(gwStaff.getGwStaffEducations())) {
            List<GwStaffEducation> gwStaffEducations = gwStaff.getGwStaffEducations();
            for (GwStaffEducation gwStaffEducation : gwStaffEducations) {
                gwStaffEducation.setStaffId(gwStaff.getId() + "");
                gwStaffEducation.setCreateTime(DateUtils.getNowDate());
                gwStaffEducation.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
                gwStaffEducation.setUpdateTime(DateUtils.getNowDate());
                gwStaffEducation.setUpdateBy(SecurityUtils.getLoginUser().getUser().getNickName());
                gwStaffEducationService.insertGwStaffEducation(gwStaffEducation);
            }
        }
        //添加工作经历
        if (ObjectUtils.isNotEmpty(gwStaff.getGwStaffWorks())) {
            List<GwStaffWork> gwStaffWorks = gwStaff.getGwStaffWorks();
            for (GwStaffWork gwStaffWork : gwStaffWorks) {
                gwStaffWork.setStaffId(gwStaff.getId() + "");
                gwStaffWork.setCreateTime(DateUtils.getNowDate());
                gwStaffWork.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
                gwStaffWork.setUpdateTime(DateUtils.getNowDate());
                gwStaffWork.setUpdateBy(SecurityUtils.getLoginUser().getUser().getNickName());
                gwStaffWorkService.insertGwStaffWork(gwStaffWork);
            }
        }
        return 1;
    }

    /**
     * 修改员工管理
     *
     * @param gwStaff 员工管理
     * @return 结果
     */
    @Override
    public int updateGwStaff(GwStaff gwStaff) {
        gwStaff.setUpdateTime(DateUtils.getNowDate());
        gwStaff.setUpdateBy(SecurityUtils.getLoginUser().getUser().getNickName());

        //删除员工信息
        gwStaffBaseService.deleteByStaffId(gwStaff.getId() + "");
        //添加员工信息
        if (ObjectUtils.isNotEmpty(gwStaff.getGwStaffBase())) {
            GwStaffBase gwStaffBase = gwStaff.getGwStaffBase();
            gwStaffBase.setCreateTime(DateUtils.getNowDate());
            gwStaffBase.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
            gwStaffBase.setUpdateTime(DateUtils.getNowDate());
            gwStaffBase.setUpdateBy(SecurityUtils.getLoginUser().getUser().getNickName());
            gwStaffBaseService.insertGwStaffBase(gwStaffBase);
        }
        //删除教育经历
        gwStaffEducationService.deleteByStaffId(gwStaff.getId() + "");
        //添加教育经历
        if (ObjectUtils.isNotEmpty(gwStaff.getGwStaffEducations())) {
            List<GwStaffEducation> gwStaffEducations = gwStaff.getGwStaffEducations();
            for (GwStaffEducation gwStaffEducation : gwStaffEducations) {
                gwStaffEducation.setStaffId(gwStaff.getId() + "");
                gwStaffEducation.setCreateTime(DateUtils.getNowDate());
                gwStaffEducation.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
                gwStaffEducation.setUpdateTime(DateUtils.getNowDate());
                gwStaffEducation.setUpdateBy(SecurityUtils.getLoginUser().getUser().getNickName());
                gwStaffEducationService.insertGwStaffEducation(gwStaffEducation);
            }
        }
        //删除工作经历
        gwStaffWorkService.deleteByStaffId(gwStaff.getId() + "");
        //添加工作经历
        if (ObjectUtils.isNotEmpty(gwStaff.getGwStaffWorks())) {
            List<GwStaffWork> gwStaffWorks = gwStaff.getGwStaffWorks();
            for (GwStaffWork gwStaffWork : gwStaffWorks) {
                gwStaffWork.setStaffId(gwStaff.getId() + "");
                gwStaffWork.setCreateTime(DateUtils.getNowDate());
                gwStaffWork.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
                gwStaffWork.setUpdateTime(DateUtils.getNowDate());
                gwStaffWork.setUpdateBy(SecurityUtils.getLoginUser().getUser().getNickName());
                gwStaffWorkService.insertGwStaffWork(gwStaffWork);
            }
        }
        return gwStaffMapper.updateGwStaff(gwStaff);
    }

    /**
     * 批量删除员工管理
     *
     * @param ids 需要删除的员工管理主键
     * @return 结果
     */
    @Override
    public int deleteGwStaffByIds(String[] ids) {
        //校验是否存在合同
        StringBuffer sb = new StringBuffer();
        for (String id : ids) {
            List<GwContract> contract = gwContractService.getGwContractByTypeAndUserId("员工关系", id, null);
            if (ObjectUtils.isNotEmpty(contract)) {
                GwStaff gwStaff = gwStaffMapper.selectGwStaffById(id);
                sb.append(gwStaff.getStaffName()).append("存在签署的合同，不能删除\n\t");
            }
        }
        if (sb.length() > 0) {
            throw new GlobalException(sb.toString());
        }
        for (String id : ids) {
            //删除员工信息
            gwStaffBaseService.deleteByStaffId(id);
            //删除教育经历
            gwStaffEducationService.deleteByStaffId(id);
            //删除工作经历
            gwStaffWorkService.deleteByStaffId(id);
        }
        return gwStaffMapper.deleteGwStaffByIds(ids);
    }

    /**
     * 删除员工管理信息
     *
     * @param id 员工管理主键
     * @return 结果
     */
    @Override
    public int deleteGwStaffById(String id) {
        return gwStaffMapper.deleteGwStaffById(id);
    }

    @Override
    public AjaxResult addByStaff(GwStaff gwStaff) throws ClientException, WxErrorException {
        if (ObjectUtils.isEmpty(gwStaff.getTel())) {
            throw new GlobalException("员工电话不能为空,操作失败");
        }
        if (ObjectUtils.isEmpty(SecurityUtils.getLoginUser().getEnterpriseId())) {
            throw new GlobalException("所属公司不能为空,操作失败");
        }

        EnterpriseInfoVO myEnterpriseInfo = gwEnterpriseInfoMapper.getLoginEnterpriseInfo(SecurityUtils.getLoginUser().getEnterpriseId());
        if (ObjectUtils.isEmpty(myEnterpriseInfo)) {
            throw new GlobalException("未知的公司，操作失败!!!");
        }
        //先保存
        insertGwStaff(gwStaff);

        // 获取小程序链接
        //String urlLink = weChatUtil.generateUrlLink("/other/staff/staffEdit", "id=" + gwStaff.getId());

        //发送短信
        //【Gowork】[企业名称]发起新员工入职信息的填写，请尽快完善。[新增员工的H5链接]
        AliyunSmsDTO aliyunSmsDTO = new AliyunSmsDTO();
        aliyunSmsDTO.setPhoneNumbers(gwStaff.getTel());
        aliyunSmsDTO.setTemplateCode("SMS_490320071");
        JSONObject json = new JSONObject();
        //设置模板参数
        json.put("company", myEnterpriseInfo.getEnterpriseName());
        json.put("staffId", gwStaff.getId());
        aliyunSmsDTO.setTemplateParam(json.toJSONString());
        sendSmsUtil.sendSms(aliyunSmsDTO);

        //增加短信数
        GwEnterpriseInfo enterpriseInfo = new GwEnterpriseInfo();
        enterpriseInfo.setId(myEnterpriseInfo.getId());
        enterpriseInfo.setSmsUseNum(myEnterpriseInfo.getSmsUseNum() + 1);
        gwEnterpriseInfoMapper.updateGwEnterpriseInfo(enterpriseInfo);

        return AjaxResult.success();
    }

    @Override
    public int editByStaff(GwStaff gwStaff) {
        gwStaff.setUpdateTime(DateUtils.getNowDate());
        //删除员工信息
        gwStaffBaseService.deleteByStaffId(gwStaff.getId() + "");
        //添加员工信息
        if (ObjectUtils.isNotEmpty(gwStaff.getGwStaffBase())) {
            GwStaffBase gwStaffBase = gwStaff.getGwStaffBase();
            gwStaffBase.setCreateTime(DateUtils.getNowDate());
            gwStaffBase.setUpdateTime(DateUtils.getNowDate());
            gwStaffBaseService.insertGwStaffBase(gwStaffBase);
        }
        //删除教育经历
        gwStaffEducationService.deleteByStaffId(gwStaff.getId() + "");
        //添加教育经历
        if (ObjectUtils.isNotEmpty(gwStaff.getGwStaffEducations())) {
            List<GwStaffEducation> gwStaffEducations = gwStaff.getGwStaffEducations();
            for (GwStaffEducation gwStaffEducation : gwStaffEducations) {
                gwStaffEducation.setStaffId(gwStaff.getId() + "");
                gwStaffEducation.setCreateTime(DateUtils.getNowDate());
                gwStaffEducation.setUpdateTime(DateUtils.getNowDate());
                gwStaffEducationService.insertGwStaffEducation(gwStaffEducation);
            }
        }
        //删除工作经历
        gwStaffWorkService.deleteByStaffId(gwStaff.getId() + "");
        //添加工作经历
        if (ObjectUtils.isNotEmpty(gwStaff.getGwStaffWorks())) {
            List<GwStaffWork> gwStaffWorks = gwStaff.getGwStaffWorks();
            for (GwStaffWork gwStaffWork : gwStaffWorks) {
                gwStaffWork.setStaffId(gwStaff.getId() + "");
                gwStaffWork.setCreateTime(DateUtils.getNowDate());
                gwStaffWork.setUpdateTime(DateUtils.getNowDate());
                gwStaffWorkService.insertGwStaffWork(gwStaffWork);
            }
        }
        return gwStaffMapper.updateGwStaff(gwStaff);
    }

}
